package com.jie.other.jetpack.room

import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.activity.viewModels
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.jie.commonlib.base.BaseActivity
import com.jie.other.BR
import com.jie.other.R
import com.jie.other.databinding.OtherActivityRoomBinding
import com.jie.other.databinding.OtherAdapterRoomListBinding
import com.jie.other.jetpack.viewmodel.RoomViewModel
import kotlinx.coroutines.flow.collectLatest

/**
 * Room框架学习测试页面
 */
class RoomActivity : BaseActivity() {

    private lateinit var mViewBinding : OtherActivityRoomBinding
    private val mViewModel by viewModels<RoomViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mViewBinding = OtherActivityRoomBinding.inflate(layoutInflater)
        setContentView(mViewBinding.root)
        initActionBar()
        initView()
        initData()
    }

    private fun initActionBar() {
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setTitle(R.string.other_room)
    }

    private fun initData() {
        lifecycleScope.launchWhenResumed {
            mViewModel.getUserList().collectLatest{
                mViewBinding.rvList.apply {
                    if (adapter == null) {
                        adapter = ListAdapter(it)
                    } else {
                        (adapter as ListAdapter).setData(it)
                    }
                }
            }
        }
    }

    private fun initView() {
        mViewBinding.run {
            btnAdd.setOnClickListener {
                mViewModel.insertUser()
            }
            btnUpdate.setOnClickListener {
                mViewModel.updateUser()
            }
            btnQueryById.setOnClickListener {
                mViewModel.queryUserById()
            }
            btnQueryByName.setOnClickListener {
                mViewModel.queryUserByName()
            }
            btnQueryAll.setOnClickListener {
                mViewModel.getAllUser()
            }
            btnDeleteAll.setOnClickListener {
                mViewModel.deleteAll()
            }
        }
    }

    class ListAdapter(private var mList : List<UserBean>?) : RecyclerView.Adapter<ListViewHolder>() {

        fun setData(list : List<UserBean>?) {
            DiffUtil.calculateDiff(UserDiffCallBack(mList, list)).apply {
                mList = list
                dispatchUpdatesTo(this@ListAdapter)
            }
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListViewHolder {
            return ListViewHolder(
                DataBindingUtil.inflate<OtherAdapterRoomListBinding>(
                LayoutInflater.from(parent.context),
                R.layout.other_adapter_room_list,
                parent,
                false
            ))
        }

        override fun getItemCount(): Int {
            return mList?.size?:0
        }

        override fun onBindViewHolder(holder: ListViewHolder, position: Int) {
            holder.viewDataBinding.setVariable(BR.item, mList!![position])
        }

    }

    class ListViewHolder(val viewDataBinding: ViewDataBinding)
        : RecyclerView.ViewHolder(viewDataBinding.root)

    class UserDiffCallBack(private val oldList: List<UserBean>?, private val newList: List<UserBean>?)
        : DiffUtil.Callback() {
        override fun getOldListSize(): Int {
            return oldList?.size?:0
        }

        override fun getNewListSize(): Int {
            return newList?.size?:0
        }

        override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
            return oldList?.get(oldItemPosition)?.userId == newList?.get(newItemPosition)?.userId
        }

        override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
            return oldList?.get(oldItemPosition)?.age == newList?.get(newItemPosition)?.age
        }

    }
}